package cn.com.headfree.base.controller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.gta.edu.sdk.base.controller.BaseController;
import com.gta.edu.sdk.common.dto.LoginUserInfo;
import com.gta.edu.sdk.util.EhCacheUtil;
import com.gta.edu.sdk.util.StringUtil;

import cn.com.headfree.base.common.MyConstant;
import cn.com.headfree.callback.call.CommRoleServerCall;
import cn.com.headfree.depterprela.service.IDeptErpRelaService;
import cn.com.headfree.entity.RoleName;
import cn.com.headfree.entity.TBusinessWorkflowBind;
import cn.com.headfree.entity.TDeptEmpRela;
import cn.com.headfree.entity.TIscRole;
import cn.com.headfree.entity.UserDeptERpRelaMsg;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.exception.HumanException;
import cn.com.headfree.util.RedisClusterUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component
public class ExBaseController extends BaseController {
	private static final Logger LOG = LogManager.getLogger(ExBaseController.class);

	@Autowired
	private CommRoleServerCall commRoleServerCall;

	@Autowired
	private IDeptErpRelaService deptErpRelaService;

	@Autowired
	private HttpServletRequest request;

	@Value("${redis.menu.timelong}")
	private int redisDomainIdTimelong;

	private String COMM_SYS_DOMAIN_ID = "9872BCFD4FBABB0DE053C6F68A0AFF47";

	@Value("${login.cacheKey}")
	private String cacheKey;

	// @ModelAttribute
	public void judgeUser() throws Exception {
		// 获取登陆用户信息
		User user = getLoginUserInfo(request);
		if (user != null) {
			if (StringUtil.isNullOrEmpty(user.getFax())) {
				LOG.info("当前登录用户无人资编号");
				throw new HumanException("当前登录用户无人资编号");
			}
		} else {
			LOG.info("当前登录用户获取失败");
			throw new HumanException("当前登录用户获取失败！");
		}
	}

	/**
	 * 根据统一权限用户nameCode获取用户对应角色信息 统一权限登录账号
	 *
	 * @return
	 */
	public User getLoginUserInfo(HttpServletRequest request) {
		User user = new User();
//        String token = getToken(request);
//        String userString = RedisClusterUtil.getInstance().getString(cacheKey + token);
        String userString = null;
        if (userString == null) {
            LOG.info("=================开始调取接口获取登录信息==================");
            LoginUserInfo loginUserInfo = this.getLongUserInfo();
            LOG.info("登录用户信息是=======================:"+loginUserInfo);
            LOG.info("调用接口获取人员信息：" + JSONArray.fromObject(loginUserInfo).toString());
            if (loginUserInfo != null) {
                user = transformLoginUser(loginUserInfo);//转换loginUser为User对象
                try {
                    //向人员信息里面加入本单位ID
                    setBaseOrgInfo(user);
                    //获取登录用户角色集合
					LOG.info("============================业务域id为======================="+COMM_SYS_DOMAIN_ID);
                    ResultData resultData = commRoleServerCall.findLabelByLoginName(loginUserInfo.getIscUserSourceId(), COMM_SYS_DOMAIN_ID);
                    if (resultData != null) {
                        LOG.info("获取当前登录人角色结果：" + JSONArray.fromObject(resultData.getData()).toString());
                        user = getRoleId(resultData, user);//调用方法获取用户最高权限角色
//                        RedisClusterUtil.getInstance().setString(cacheKey + token, JSONObject.fromObject(user).toString(), redisDomainIdTimelong);
//                        this.getRoleListForJson(resultData.getData()); //获取用户角色json数据入库-add by yangwang 20200707
                    } else {
                        LOG.info("获取当前登录人角色失败！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            else {
//				user.setBaseOrgId("10342674");
//				user.setBaseOrgName("国网安徽省电力有限公司信息通信分公司");
//				user.setDeptId("10347064");
//				user.setDeptName("综合管理部");
//				user.setName("程媛媛");
//				user.setFax("30132685");
//				user.setRemark("2");//普通用户
//				user.setTitle("普通用户");
//				user.setHomePostalCode("xt_rz,ixt_dw_admin");
//				user.setId("39AE8ED108BB00EAE0530A8A018B00EA");

//              user.setBaseOrgId("10333706");

//				user.setBaseOrgId("10343134");
//                user.setBaseOrgName("国网安徽省电力有限公司综合服务中心");
//                user.setDeptId("10347034");
//                user.setDeptName("人力资源服务部");
//                user.setName("彭琪");
//                user.setFax("11234289");
//                user.setRemark("2");//普通用户
//                user.setTitle("普通用户");
//                user.setHomePostalCode("xt_rz,ixt_dw_admin");
//                user.setId("F2EC41EDE1680086E0430A8A018B0086");


//
				user.setBaseOrgId("10333706");
                user.setBaseOrgName("国网宣城供电公司本部");
                user.setDeptId("10346626");
                user.setDeptName("党委组织部（人力资源部）");
                user.setName("吴小虎");
                user.setFax("11188338");
                user.setRemark("2");//普通用户
                user.setTitle("普通用户");
                user.setHomePostalCode("xt_rz,ixt_dw_admin");
                user.setId("F2EC41ECE6510086E0430A8A018B0086");
            }
        } else {
            user = (User) JSONObject.toBean(JSONObject.fromObject(userString), User.class);
        }
        LOG.info("获取当前登录人信息结果：" + JSONObject.fromObject(user).toString());
        return user;
    }

	/**
	 * 转换接口调用获取的user为本系统需要的用户对象
	 * @return
	 */
	public User transformLoginUser(LoginUserInfo loginUserInfo) {
		User user = new User();
//        String erpNo = this.getErpNoOfCurUser();
        // 先调用本地表isc_user获取fax字段值
        UserDeptERpRelaMsg userDeptERpRelaMsg = this.getInfoOfCurUser(loginUserInfo);
        String erpNo = userDeptERpRelaMsg.getErpNo();
        user.setId(loginUserInfo.getIscUserId());
        user.setName(userDeptERpRelaMsg.getUserName());
        user.setBaseOrgId(loginUserInfo.getBaseOrgId());
        user.setOrgAnisationName(loginUserInfo.getBaseOrgName());
        user.setUserName(loginUserInfo.getIscUserSourceId());
        if (!StringUtil.isNullOrEmpty(userDeptERpRelaMsg.getErpNo())) {
            user.setFax(erpNo);
        } else {//如果本地fax为空 就调用公共接口获取
            erpNo = getLoginUserFax(loginUserInfo.getIscUserId());//根据userId调接口获取fax字段
            if (!StringUtil.isNullOrEmpty(erpNo)) {
                user.setFax(erpNo);
            }
        }
        return user;
    }

	/**
	 * 根据userId调接口获取fax字段
	 *
	 * @param userId
	 * @return
	 */
	public String getLoginUserFax(String userId) {
		LoginUserInfo loginUserInfo = new LoginUserInfo();
		String erpNo = "";
		ResultData resultData = commRoleServerCall.findUserByUserId(userId);
		if (resultData != null) {
			LOG.info("调用接口获取Fax字段值返回数据：" + JSONObject.fromObject(resultData).toString());
			if (resultData.getData() != null) {
				loginUserInfo = (LoginUserInfo) JSONObject.toBean(JSONObject.fromObject(resultData.getData()),
						LoginUserInfo.class);
				if (!StringUtil.isNullOrEmpty(loginUserInfo.getFax()) && !"暂无".equals(loginUserInfo.getFax())) {
					erpNo = loginUserInfo.getFax();
				}
			}
		}
		return erpNo;
	}

	/**
	 * @Description: 解析获取当前用户角色 edit by yangwang 20200706
	 * @Param:
	 * @return:
	 * @Author: panl
	 * @createTime: 2020/7/5 13:58
	 */
	public User getRoleId(ResultData resultData, User user) throws SQLException {
		LOG.info("=========开始解析当前用户最高权限角色=========");
		if (resultData.getData() == null) {
			return user;
		}
		JSONArray jsonArray = JSONArray.fromObject(resultData.getData());
		String roleID = "";
		String roleName = "";
		int num = 0;
		List<TIscRole> iscRoleList = new ArrayList<TIscRole>();
		TIscRole role = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObjectUser = JSONObject.fromObject(jsonArray.get(i));
			roleID = jsonObjectUser.get("code").toString();
			roleName = jsonObjectUser.get("name").toString();
			LOG.info("当前用户roleID:" + roleID + ";roleName:" + roleName);
			if (MyConstant.USER_ROLETYPE_PUTONG.equals(roleID)) {
				if (num <= 1) {
					user.setRemark("1");
					user.setTitle(roleName);
					num = 1;
				}
			}
			if (MyConstant.USER_ROLETYPE_DANWEI.equals(roleID)) {
				if (num <= 2) {
					user.setRemark("2");
					user.setTitle(roleName);
					num = 2;
				}
			}
			if (MyConstant.USER_ROLETYPE_SHEN.equals(roleID)) {
				if (num <= 3) {
					user.setRemark("3");
					user.setTitle(roleName);
					num = 3;
				}
			}
			// 添加人员角色集合

			if (num == 2) {
				role = new TIscRole();
				role.setId(jsonObjectUser.getString("id"));
				role.setName(jsonObjectUser.getString("name"));
				role.setCode(jsonObjectUser.getString("code"));
				iscRoleList.add(role);
			}
		}
		LOG.info("=========解析当前用户最高权限角色完成=========");

		// 获取当前登录人的审核角色
		user = addAuditRoleList(resultData, user);
		// 实时保存角色信息到数据库
		if ((null != iscRoleList) && (0 < iscRoleList.size())) {
			deptErpRelaService.saveIscRole(iscRoleList);
		}
		return user;
	}

	// 人员角色清单
	private User addAuditRoleList(ResultData resultData, User user) {
		try {
			JSONArray jsonArray = JSONArray.fromObject(resultData.getData());
			String roleID = "";
			String roleName = "";
			String roleList = "";
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObjectUser = JSONObject.fromObject(jsonArray.get(i));
				roleID = jsonObjectUser.get("code").toString();
				roleName = jsonObjectUser.get("name").toString();
				LOG.info("当前用户roleID:" + roleID + ";roleName:" + roleName);
				// 排除系统角色，审核角色用”,“分割
				if (!(MyConstant.USER_ROLETYPE_PUTONG.equals(roleID) || MyConstant.USER_ROLETYPE_DANWEI.equals(roleID)
						|| MyConstant.USER_ROLETYPE_SHEN.equals(roleID))) {
					roleList += roleID + ",";
				}
			}
			// 添加当前登录人审核角色
			user.setHomePostalCode(roleList);
		} catch (Exception ex) {
			LOG.error("获取登录人审核角色失败：" + ex.getMessage());
		}
		return user;
	}

	/**
	 * 获取当前登陆人的erp编码
	 *
	 * @return String
	 * @author yangwang
	 */
	public String getErpNoOfCurUser() {
		String erpNo = null;
		// 获取用户登录信息
		LoginUserInfo loginUser = this.getLongUserInfo();
		if ((null != loginUser) && (StringUtils.isNotBlank(loginUser.getIscUserId()))) {
			List<UserDeptERpRelaMsg> userList = deptErpRelaService.getErpNoByUserIds(loginUser.getIscUserId());
			if ((null != userList) && (0 < userList.size())) {
				erpNo = userList.get(0).getErpNo();
			}
		}
		return erpNo;
	}

	/**
	 * 获取当前登陆人的erp编码和姓名
	 *
	 * @return String
	 * @author yangwang
	 */
	public UserDeptERpRelaMsg getInfoOfCurUser() {
		UserDeptERpRelaMsg userDeptERpRelaMsg = new UserDeptERpRelaMsg();
		// 获取用户登录信息
		LoginUserInfo loginUser = this.getLongUserInfo();
		if ((null != loginUser) && (StringUtils.isNotBlank(loginUser.getIscUserId()))) {
			List<UserDeptERpRelaMsg> userList = deptErpRelaService.getErpNoByUserIds(loginUser.getIscUserId());
			if ((null != userList) && (0 < userList.size())) {
				userDeptERpRelaMsg = userList.get(0);
			}
		}
		return userDeptERpRelaMsg;
	}

    /**
     * 获取当前登陆人的erp编码和姓名
     *
     * @return String
     * @author yangwang
     */
    public UserDeptERpRelaMsg getInfoOfCurUser(LoginUserInfo loginUser) {
        UserDeptERpRelaMsg userDeptERpRelaMsg = new UserDeptERpRelaMsg();
        //获取用户登录信息
//        LoginUserInfo loginUser = this.getLongUserInfo();
        if ((null != loginUser) && (StringUtils.isNotBlank(loginUser.getIscUserId()))) {
            List<UserDeptERpRelaMsg> userList = deptErpRelaService.getErpNoByUserIds(loginUser.getIscUserId());
            if ((null != userList) && (0 < userList.size())) {
                userDeptERpRelaMsg = userList.get(0);
            }
        }
        return userDeptERpRelaMsg;
    }

    /**
     * 根据信息分类id获取角色下所有用户信息
     *
     * @param businessTypeId 信息分类id
     * @return ResultData
     * @throws SQLException
     * @author yangwang
     */
    public ResultData getUsersByBusinessTypeId(String businessTypeId) throws SQLException {
        ResultData result = new ResultData();
        //获取用户登录信息
        User loginUser = this.getLoginUserInfo(request);
        if ((null != loginUser)) {
            //获取角色编码
            LOG.info("=====================111111=============" + businessTypeId);
            LOG.info("=====================222222222=============" + loginUser.getBaseOrgId());
            TBusinessWorkflowBind businessBind = deptErpRelaService.getBusinessBind(new TBusinessWorkflowBind(businessTypeId, loginUser.getBaseOrgId()));
            if ((null != businessBind) && (StringUtils.isNotBlank(businessBind.getId())) && (StringUtils.isNotBlank(businessBind.getDealRoleId()))) {
                LOG.info("=========================333333=========================");
                //根据code获取角色信息
                List<TIscRole> roleList = deptErpRelaService.getIscRoleByCode(businessBind.getDealRoleId());
                LOG.info("=========================444444444=========================" + roleList.size());
                if ((null != roleList) && (0 < roleList.size())) {//已存库
                    //根据角色ID获得角色下所有的人员信息
                    return commRoleServerCall.findUserByLabelId(roleList.get(0).getId(), COMM_SYS_DOMAIN_ID);
                } else {//未存库
                    LOG.info("=========================5555555555=========================");
                    //根据用户ID和应用ID获取业务域
                    ResultData roleData = commRoleServerCall.findLabelByDomainId(COMM_SYS_DOMAIN_ID, 100, 1);

//                    ResultData roleData = commRoleServerCall.findLabelByLoginName(loginUser.getUserName(), this.getToken(request));
					// 获取用户角色json数据入库,且此时要取流程配置的角色code(每种信息类别的配置的流程的code)
					List<TIscRole> roleDatas = this.getRoleListForJson(roleData.getData(),
							businessBind.getDealRoleId());
					if ((null != roleDatas) && (0 < roleDatas.size())) {
						// 查找到匹配的角色
						Optional<TIscRole> opt = roleDatas.stream()
								.filter(r -> ((null != r) && (StringUtils.isNotBlank(r.getId()))
										&& (StringUtils.equals(r.getCode(), businessBind.getDealRoleId()))))
								.findFirst();
						if ((opt.isPresent()) && (StringUtils.isNotBlank(opt.get().getId()))) {
							LOG.info("=========================6666666666666========================="
									+ roleDatas.size());
							LOG.info("=========================777777777777777========================="
									+ roleDatas.get(0).getId());
							// 根据角色ID获得角色下所有的人员信息
                            return commRoleServerCall.findUserByLabelId(opt.get().getId(), COMM_SYS_DOMAIN_ID);

						}
					}
				}
			}
		}

		return result;
	}

	/**
	 * 获取用户角色json数据入库
	 *
	 * @param josn
	 * @return List<TIscRole>
	 * @throws SQLException
	 * @author yangwang
	 */
	private List<TIscRole> getRoleListForJson(Object josn, String code) throws SQLException {
		List<TIscRole> roleList = new ArrayList<>();
		if (null != josn) {
			LOG.info("===========================8888888888888888888888==========================");
			JSONObject jsonObject = JSONObject.fromObject(josn);
			Object object = jsonObject.get("data");
			LOG.info("=====================" + object.toString() + "================================");
			if (object != null) {
				LOG.info("===========================999999999999999999999999999==========================");
				JSONArray jsonArray = JSONArray.fromObject(object);
				LOG.info("=====================" + jsonArray.toString() + "================================");
				if ((null != jsonArray) && (0 < jsonArray.size())) {
					TIscRole role = null;
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject obj = (JSONObject) jsonArray.get(i);

						if (null != obj) {
							if (code.equals(obj.getString("code"))) {
								role = new TIscRole();
								role.setId(obj.getString("id"));
								role.setName(obj.getString("name"));
								role.setCode(obj.getString("code"));
								roleList.add(role);
							}
						}
					}
				}
			}

			// 实时保存角色信息到数据库
			if ((null != roleList) && (0 < roleList.size())) {
				deptErpRelaService.saveIscRole(roleList);
			}
		}
		return roleList;
	}

	public String getToken(HttpServletRequest req) {
//		String token = null;
//		Cookie[] cookies = req.getCookies();
//		if ((null != cookies) && (0 < cookies.length)) {
//			for (Cookie cookie : cookies) {
//				if ((null != cookie) && StringUtils.isNotBlank(cookie.getName())
//						&& StringUtils.equals(cookie.getName(), "token") && StringUtils.isNotBlank(cookie.getValue())) {
//					token = cookie.getValue();
//					LOG.info("从request获取token信息为：" + token);
//					break;
//				}
//			}
//		}
		String token = this.getTicket();
		LOG.info("调取公共框架获取TOKEN值是:" + token);
		return token;
	}

	/**
	 * 通过用户ID获取用户角色
	 *
	 * @param token
	 * @param loginCode 登录账号
	 * @return
	 */
	public String getUserRole(String token, String loginCode) {
		// 从缓存获取
		String result = EhCacheUtil.getValue(loginCode);
//        if (!StringUtil.isNullOrEmpty(result)) {
//            return result;
//        }
//        result = RedisClusterUtil.getInstance().getString(loginCode);
//        if (!StringUtil.isNullOrEmpty(result)) {
//            EhCacheUtil.put(MyConstant.CACHE_KEY_ROLE + loginCode, result);
//            return result;
//        }
		// 缓存查不到 调用接口查询
		List<RoleName> roleNames = getRoleNameList(token);
		List<String> roleNameList = new ArrayList<>();
		if (roleNames != null && roleNames.size() > 0) {
			for (RoleName item : roleNames) {
				String roleName = getRoleByLabelId(item, token, loginCode);
				if (roleName != null) {
					roleNameList.add(roleName);
				}
			}
		}
		// 获取权限最大的角色
		result = getTopRole(roleNameList);
//		// 放入缓存
//		if (!StringUtil.isNullOrEmpty(result)) {
//			EhCacheUtil.put(MyConstant.CACHE_KEY_ROLE + loginCode, result);
//			RedisClusterUtil.getInstance().setString(MyConstant.CACHE_KEY_ROLE + loginCode, result,
//					MyConstant.REDIS_ROLE_TIMEOUT);
//		}
		return result;
	}

	/**
	 * 调用用户ID获取用户角色接口
	 *
	 * @param token
	 * @return
	 */
	public List<RoleName> getRoleNameList(String token) {
		List<RoleName> result = null;
		try {
			// 从缓存获取
//			String json = EhCacheUtil.getValue(MyConstant.CACHE_KEY_ROLE_JSON);
//			if (!StringUtil.isNullOrEmpty(json)) {
//				result = getRoleNameListForJson(json);
//				return result;
//			}
//			json = RedisClusterUtil.getInstance().getString(MyConstant.CACHE_KEY_ROLE_JSON);
//			if (!StringUtil.isNullOrEmpty(json)) {
//				EhCacheUtil.put(MyConstant.CACHE_KEY_ROLE_JSON, json);
//				result = getRoleNameListForJson(json);
//				return result;
//			}

			// 根据用户ID和应用ID获取业务域
			ResultData resultData = commRoleServerCall.findLabelByDomainId(COMM_SYS_DOMAIN_ID, 100, 1);
			if (null != resultData) {
				LOG.info("获取数据为--" + resultData.toString());
				if (null != resultData.getData()) {
					// 放入缓存
//					EhCacheUtil.put(MyConstant.CACHE_KEY_ROLE_JSON, resultData.getData().toString());
//					RedisClusterUtil.getInstance().setString(MyConstant.CACHE_KEY_ROLE_JSON,
//							resultData.getData().toString(), MyConstant.REDIS_ROLE_TIMEOUT);
					result = getRoleNameListForJson(resultData.getData());
				}
			} else {
				LOG.info("未找到对应的数据字段");
			}
		} catch (Exception e) {
			LOG.error("调用用户ID获取用户角色接口失败", e);
		}

		return result;
	}

	/**
	 * 根据角色ID获得角色下所有的人员信息
	 *
	 * @param roleName
	 * @param token
	 * @param loginCode
	 * @return
	 */
	public String getRoleByLabelId(RoleName roleName, String token, String loginCode) {
		String result = null;
		try {
			// 根据用户ID和应用ID获取业务域
			ResultData resultData = commRoleServerCall.findUserByLabelId(roleName.getLabelId(), COMM_SYS_DOMAIN_ID);
			if (null != resultData) {
				LOG.info("获取数据为--" + resultData.toString());
				if (null != resultData.getData()) {
					JSONArray jsonArray = JSONArray.fromObject(resultData.getData());
					if ((null != jsonArray) && (0 < jsonArray.size())) {
						for (int i = 0; i < jsonArray.size(); i++) {
							JSONObject obj = (JSONObject) jsonArray.get(i);
							if (null != obj) {
								if (obj.getString("loginName") != null
										&& loginCode.equals(obj.getString("loginName"))) {
									result = roleName.getCode();
									break;
								}
							}
						}
					}
				}
			} else {
				LOG.info("未找到对应的数据字段");
			}
		} catch (Exception e) {
			LOG.error("调用用户ID获取用户角色接口失败", e);
		}

		return result;
	}

	/**
	 * 解析json-调用用户ID获取用户角色接口
	 *
	 * @param josn
	 * @return
	 * @throws SQLException
	 */
	private List<RoleName> getRoleNameListForJson(Object josn) throws SQLException {
		List<RoleName> roleNames = new ArrayList<>();
		JSONArray jsonArray = JSONArray.fromObject(josn);
		if ((null != jsonArray) && (0 < jsonArray.size())) {
			List<TIscRole> iscRoleList = new ArrayList<TIscRole>();
			TIscRole role = null;
			RoleName roleName = null;
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject obj = (JSONObject) jsonArray.get(i);
				if (null != obj) {
					roleName = new RoleName();
					roleName.setLabelId(obj.getString("domainId"));
					roleName.setName(obj.getString("name"));
					roleName.setCode(obj.getString("code"));
					roleNames.add(roleName);
					role = new TIscRole();
					role.setId(obj.getString("domainId"));
					role.setName(obj.getString("name"));
					role.setCode(obj.getString("code"));
					iscRoleList.add(role);
				}
			}
			// 实时保存角色信息到数据库
			if ((null != iscRoleList) && (0 < iscRoleList.size())) {
				deptErpRelaService.saveIscRole(iscRoleList);
			}
		}
		return roleNames;
	}

	/**
	 * 获取用户角色中级别最高的角色
	 *
	 * @param roleList
	 * @return
	 */
	private String getTopRole(List<String> roleList) {
		String result = null;
		if (roleList != null && roleList.size() > 0) {
			if (roleList.contains(MyConstant.USER_ROLETYPE_SHEN)) {
				result = MyConstant.USER_ROLETYPE_SHEN;
			} else if (roleList.contains(MyConstant.USER_ROLETYPE_DANWEI)) {
				result = MyConstant.USER_ROLETYPE_DANWEI;
			} else if (roleList.contains(MyConstant.USER_ROLETYPE_PUTONG)) {
				result = MyConstant.USER_ROLETYPE_PUTONG;
			}
		}
		return result;
	}

	/**
	 * 向登录人里面加入本单位信息
	 */
	private void setBaseOrgInfo(User user) {
		List<TDeptEmpRela> deptEmpRelas = deptErpRelaService.getOrgIdByErpNo(user.getFax());
		if (deptEmpRelas != null && deptEmpRelas.size() > 0) {
			user.setBaseOrgId(deptEmpRelas.get(0).getOrgId());//单位ID
			user.setBaseOrgName(deptEmpRelas.get(0).getOrgName());
			user.setDeptId(deptEmpRelas.get(0).getDeptId());//部门ID（末级部门）
			LOG.info("============isHeadDept为=========="+deptEmpRelas.get(0).getIsHeadDept());
			if (deptEmpRelas.get(0).getIsHeadDept() != null) {
				user.setIsHeadDept(deptEmpRelas.get(0).getIsHeadDept());
				LOG.info("============user中isHeadDept为=========="+user.getIsHeadDept());
			}else{
				user.setIsHeadDept(null);
				LOG.info("============user中isHeadDept为null=========="+user.getIsHeadDept());
			}
			if (deptEmpRelas.get(0).getpId() != null) {
				user.setpId(deptEmpRelas.get(0).getpId());
			}
		}
	}

}
